<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>栈的封装</title>
</head>

<body>
    <script>
        function Stack() {
            this.items = [];
            // 入栈
            Stack.prototype.push = function (element) {
                this.items.push(element)
            }
            //出栈
            Stack.prototype.pop = function () {
                return this.items.pop()
            }
            //返回栈顶元素
            Stack.prototype.peek = function () {
                return this.items[this.items.length - 1]
            }
            //栈是否为空
            Stack.prototype.isEmpty = function () {
                return this.items.length === 0 ? true : false
            }
            //栈的长度
            Stack.prototype.size = function () {
                return this.items.length
            }
            //
            Stack.prototype.toString = function () {
                let resultString = ''
                for (let i of this.items) {
                    resultString += i + ' '
                }
                return resultString
            }
        }
        // let s = new Stack()
        // s.push(20)
        // s.push(10)
        // s.push(100)
        // s.push(77)
        //console.log(s)												

        // console.log(s.pop());
        // console.log(s.pop());

        // console.log(s.peek());
        // console.log(s.isEmpty());

        // console.log(s.size());
        // console.log(s.toString());
        let s = new Stack()
        function decimalToBinary(decimal) {

            while (decimal > 0) {
                s.push(decimal % 2);
                decimal = parseInt(decimal / 2);
            }
            var binary = ''
            while (!s.isEmpty()) {
                binary += s.pop()
            }
            return binary
        }
        console.log(decimalToBinary(8)); 
    </script>
</body>

</html>